package com.dhnsoft.education.controller.order;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dhnsoft.education.entity.edu.EduCourse;
import com.dhnsoft.education.entity.order.Order;
import com.dhnsoft.education.service.edu.EduCourseService;
import com.dhnsoft.education.service.order.OrderService;
import com.dhnsoft.education.service.order.PayLogService;
import com.dhnsoft.education.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 支付日志表 前端控制器
 * </p>
 *
 * @author 代浩楠
 * @since 2022-04-14
 */
@RestController
@RequestMapping("/eduorder/payLog")
//@CrossOrigin
public class PayLogController {

    @Autowired
    private PayLogService payLogService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private EduCourseService courseService;

    //生成微信支付二维码
    @GetMapping("createNative/{orderNo}")
    public R createNative(@PathVariable String orderNo){
        //返回信息，包含二维码地址和其他信息
        Map map = payLogService.createNative(orderNo);
        System.out.println("返回二维码map集合:"+map);
        return R.ok().data(map);
    }

    //查询订单支付状态
    //参数：订单号，根据订单号查询 支付状态
    @GetMapping("queryPayStatus/{orderNo}")
    public R queryPayStatus(@PathVariable String orderNo){
        Map<String,String> map = payLogService.queryPayStatus(orderNo);
        System.out.println("***查询订单状态map集合:"+map);
        if(map==null){
            return R.error().message("支付出错了!");
        }
        //如果返回map里面不为空,通过map获取订单状态
        if(map.get("trade_state").equals("SUCCESS")){
            //添加记录到支付表，更新订单表订单状态
            payLogService.updateOrderStatus(map);
            //根据订单号查询课程号
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            Order byId = orderService.getOne(wrapper);
            String courseId = byId.getCourseId();
            //更新课程表的购买数
            EduCourse course = courseService.getById(courseId);
            course.setBuyCount(course.getBuyCount()+1);
            courseService.updateById(course);
            return R.ok().data("success",10000).message("支付成功!");
        }
        return R.ok().code(25000).message("支付中!");
    }

}

